<?php

/**
 * @description:
 * @author sunnyw<iwisunny@gmail.com>
 * @property User_model  $user
 * @property Group_model $group
 */
class Login extends Base_Controller
{

    protected $role_list;

    const ADMIN_GROUP=1;

    function __construct()
    {
        parent::__construct();
        $this->load->model('user_model', 'user');
    }

    function index()
    {
        $this->login();
    }

    function login()
    {
        if($this->session->userdata('username')){
            redirect(base_url());
        }

        if (is_xhr()) {
            $data = $this->input->post_get('entity', true);

            $username = $data['username'];
            $passwd = $data['password'];

            $check_user = $this->user->get_by('username', $username);
            if (empty($check_user)) {
                $this->put_msg(array('info' => '用户不存在'));
            }

            $orig_pass = $check_user['password'];
            $hash_pass = md5($check_user['salt'] . $passwd);

            if ($orig_pass !== $hash_pass) {
                $this->put_msg(array('info' => '密码错误'));
            }

            $this->user->skip_validation();
            $status = $this->user->update($check_user['id'], $check_user);
            if ($status === true) {
                //update session
                $this->session->set_userdata(array(
                    'username'   => $username,
                    'pass'       => $hash_pass,
                    'last_login' => $check_user['last_login'],
                    'is_admin'=> $check_user['group_id']==self::ADMIN_GROUP
                ));
            }

            $this->set_msg('success', true)->put_msg();

        }

        $this->tpl->render('login.twig', array(
            'login_page' => true
        ));
    }



    function logout()
    {
        if(is_xhr()){
            $this->session->unset_userdata(array('username', 'pass', 'last_login','is_admin'));
            $status=null==$this->session->userdata('username');
            $this->put_msg([
                'success'=>$status
            ]);
        }

        $this->put_msg();
    }
}